﻿using System;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
// 一般情况下都是操作相对于父节点的旋转
public class RotateCanvas : MonoBehaviour
{
    public Transform goTransform;
    public Transform capsuleTransform;
    public Text wordRotation;
    public Text localRotation;
    public int speed = 100;
    private void Start()
    {
        ShowEulerAngles();
    }

    public void OnRotateBtnClick(string axis) 
    {
        speed = 0;
        switch (axis)
        {
            case "x":
                goTransform.Rotate(Vector3.right,90 ,Space.Self);    
                break;
            case "y":
                goTransform.Rotate(Vector3.up,90,Space.Self); 
                break;
            case "z":
                goTransform.Rotate(Vector3.forward,90, Space.Self); 
                break;
        }
        ShowEulerAngles();
    }

    public void OnRotateBtnClick()
    {
        speed = 0;
        // 围绕 z 轴旋转 90 度、围绕 x 轴旋转 90 度、围绕 y 轴旋转 90 度（按该顺序应用）
        Quaternion rotationNew = Quaternion.Euler(new Vector3(90, 90, 90));
        goTransform.localRotation = rotationNew;
        ShowEulerAngles();
    }

    // 恢复到没有旋转
    public void OnResetBtnClick()
    {
        goTransform.localRotation = Quaternion.identity;
        ShowEulerAngles();
        speed = 100;
    }

    private void ShowEulerAngles()
    {
        wordRotation.text = goTransform.eulerAngles.ToString();
        localRotation.text = goTransform.localEulerAngles.ToString();
        GetInspectorRotationValue(goTransform);
    }
    
    // 打印Inspector 面板的旋转值 
    public void GetInspectorRotationValue(Transform transform)
    {
        System.Type transformType = transform.GetType();
        PropertyInfo m_propertyInfo_rotationOrder = transformType.GetProperty("rotationOrder", BindingFlags.Instance | BindingFlags.NonPublic);
        object m_OldRotationOrder = m_propertyInfo_rotationOrder.GetValue(transform, null);
        MethodInfo m_methodInfo_GetLocalEulerAngles = transformType.GetMethod("GetLocalEulerAngles", BindingFlags.Instance | BindingFlags.NonPublic);
        object value = m_methodInfo_GetLocalEulerAngles.Invoke(transform, new object[] { m_OldRotationOrder });
        //获取的真实值
        Debug.Log("反射调用GetLocalEulerAngles方法获得的值：" + value.ToString());
    }

    private void Update()
    {
        capsuleTransform.Rotate(Time.deltaTime * speed * Vector3.up  );
    }
}
